<?php

namespace App\Http\Controllers\Admin\Goods;

use Illuminate\Http\Request;
use App\Models\Goods\Speci;
use Illuminate\Support\Facades\Session;
use App\Models\Goods\Goods AS GoodsModel;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;


class GoodsController extends Controller
{
    /**
     * 商品列表--goods
     */
    public function goods(){
        return view('admin.goods.goods.goods');

    }

    /**
     * 商品管理--sku
     */
    public function speci(){
        return view('admin.goods.speci.speci');
    }

    /**
     * 商品分类--category
     */
    public function category(){
        return view('admin.goods.category.category');

    }

    public function add(Request $request){

        $speci = Speci::all();

        return view('admin.goods.goods.add')->with(['speci'=>$speci]);
    }

    public function addGoods(Request $request){

        $res = $request->all();

        //插入数据到商品主表
        $data = $res['goods'];
        $data_tmp = explode(',',$data['category_all_id']) ;
        $data['category_id'] = end($data_tmp ) ;
        unset($data['file']);
        $goods_id = DB::table('goods')->insertGetId($data);

        //插入sku表
        $data_sku_arr = addArrayKV(['goods_id'=>$goods_id],$res['sku']);
        DB::table('goods_sku')->insert($data_sku_arr);

        //根据sku第一条信息更新主表sku相关字段
        $goods_sku_res =  DB::table('goods_sku')->where('goods_id', $goods_id)->get();
        $stock=0;
        foreach ($goods_sku_res as $v){
            $stock += $v->stock;
        }
        $goods_update = [
            'price'=>$goods_sku_res[0]->price,
            'stock'=>$stock,
            'sku_id'=>$goods_sku_res[0]->id,
        ];
        $res = DB::table('goods')->where('id', $goods_id)->update($goods_update);
        if($res){
            return showMsg(200,'提交成功');
        }else{
            return showMsg(0,'提交失败');
        }
    }



}
